<?php

/**
 * 百度OAuth登录回调
 * 
 * @author ShuangYa
 * @package EUser
 * @category Controller
 * @link http://www.sylingd.com/
 * @copyright Copyright (c) 2015-2016 ShuangYa
 * @license http://lab.sylingd.com/go.php?name=euser&type=license
 */

namespace euser\libs\oauth;
use \Sy;
use \sy\lib\YFetchURL;

class Baidu {
	protected $config;
	protected static $_instance = NULL;
	protected static $_cfg = NULL;
	public static function i($config) {
		$cfgkey = md5(implode(',', $config));
		if (self::$_instance === NULL || self::$_cfg !== $cfgkey) {
			self::$_cfg === $cfgkey;
			self::$_instance = new self($config);
		}
		return self::$_instance;
	}
	public function __construct($config) {
		$this->config = $config;
	}
	public function getAuthorizeUrl() {
		return 'https://openapi.baidu.com/oauth/2.0/authorize?' . http_build_query(['response_type' => 'code', 'client_id' => $this->config['id'], 'redirect_uri' => $this->getReditectUri()]);
	}
	public function getReditectUri() {
		return Sy::createUrl(['oauthclient/callback', 'client' => 'baidu']);
	}
	public function callback($code) {
		if (empty($code)) {
			return FALSE;
		}
		//换取Token
		$httpData = [
			'grant_type' => 'authorization_code',
			'code' => $code,
			'client_id' => $this->config['id'],
			'client_secret' => $this->config['secret'],
			'redirect_uri' => $this->getReditectUri()
		];
		$token = YFetchURL::i([
			'url' => 'https://openapi.baidu.com/oauth/2.0/token?' . http_build_query($httpData),
			'header' => 0
		])->exec();
		if (empty($token)) {
			return FALSE;
		}
		$token = json_decode($token, 1);
		//换取用户信息
		$baiduUser = YFetchURL::i([
			'url' => 'https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser?' . http_build_query([
				'access_token' => $token['access_token'],
				'format' => 'json'
			]),
			'header' => 0
		])->exec();
		$baiduUser = json_decode($baiduUser, 1);
		if (!is_array($baiduUser)) {
			return FALSE;
		}
		$result = [
			'type' => 1,
			'id' => $baiduUser['uid'],
			'name' => $baiduUser['uname'],
			'avatar' => $baiduUser['portrait'],
			'token' => $token['access_token']
		];
		return $result;
	}
}